package com.example.myapplication

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.text.TextUtils
import android.view.View
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.content.FileProvider
import com.bumptech.glide.Glide
import com.dream.antiquities.utils.CopyFileByUri
import com.example.myapplcation.entity.PopularScienceMineEntity
import com.example.myapplcation.fragment.BaseActivity
import com.example.myapplication.database.DataBaseUtils
import com.example.total.databinding.ActivityAddPopularScienceBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File


class AddPopularScienceActivity : BaseActivity<ActivityAddPopularScienceBinding>() {
    private val launcher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
        if (isGranted) {
            startCamera()
        }else{
            Toast.makeText(this,"打开相机权限才能使用",Toast.LENGTH_SHORT).show()
        }
    }
    override fun initData() {
        binding.addImage.setOnClickListener {
            openPhoto()
        }
        binding.save.setOnClickListener {
            if(uri==null&&cameraImageFile==null){
                Toast.makeText(this,"图片不能为空",Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if(TextUtils.isEmpty(binding.name.text.toString().trim())){
                Toast.makeText(this,"文物名称不能为空",Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if(TextUtils.isEmpty(binding.describe.text.toString().trim())){
                Toast.makeText(this,"文物简介不能为空",Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            //保存
            GlobalScope.launch(Dispatchers.IO){
                imagePath = if(uri!=null){
                    CopyFileByUri.getPath(this@AddPopularScienceActivity,uri!!)
                }else{
                    cameraImageFile!!.absolutePath
                }
                DataBaseUtils.getInstance(this@AddPopularScienceActivity)
                    .dataBaseDao()
                    .insertPopularScience(PopularScienceMineEntity(imagePath,binding.name.text.toString().trim(),binding.describe.text.toString().trim()))
                withContext(Dispatchers.Main){
                    Toast.makeText(this@AddPopularScienceActivity,"保存成功",Toast.LENGTH_SHORT).show()
                    finish()
                }
            }
        }
    }

    private fun openPhoto() {
        ChoosePhotoDialog(this).setCamera{
            openCamera()
        }.setPhoto {
            val albumIntent = Intent(Intent.ACTION_PICK);
            albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(albumIntent, 100)
        }.show()
    }

    private fun openCamera() {
        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
            launcher.launch(Manifest.permission.CAMERA)
        }else{
            startCamera()
        }
    }
    private var cameraImageFile:File?= null
    private fun startCamera(){
        cameraImageFile = createImageUri()
        val photoUri = FileProvider.getUriForFile(
            this,
            applicationContext.packageName + ".fileprovider",
            cameraImageFile!!
        )

        val captureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
        captureIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
        val resInfoList =
            packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
        resInfoList.forEach {
            val packageName: String = it.activityInfo.packageName
            grantUriPermission(packageName, photoUri,
                Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
        }
        startActivityForResult(captureIntent, 200)
    }
    private var imagePath:String = ""
    private var uri: Uri? = null
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==200&&resultCode==Activity.RESULT_OK){
            Glide.with(this).load(cameraImageFile)
                .into(binding.cover)
            binding.addImage.visibility = View.GONE
            binding.cover.setOnClickListener {
                openPhoto()
            }
            uri=null
        }
        if (data == null) return
        if(requestCode==100&&resultCode==Activity.RESULT_OK){
            uri = data.data
            uri?.let {
                Glide.with(this).load(it)
                    .into(binding.cover)
            }
            binding.addImage.visibility = View.GONE
            binding.cover.setOnClickListener {
                openPhoto()
            }
            cameraImageFile =null
        }
    }

    private fun createImageUri(): File {
        val storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        return File.createTempFile(
            "temp",  /* 文件名称 */
            ".jpg",  /* 文件后缀 */
            storageDir /* 存储目录 */
        )
    }
}